/*
 Authors: ZhangXuelian
 	
 
 Changes:
 	
	
*/


#include "../libmain/gobal.h"

bool init_mq()
{
	SDK_CONTENT * c = &g_sdk_content;
	c->mq.client.tcpkeepalive = CONFIG_DEFAULT_TCP_KEEPALIVE;
	c->mq.client.flag = FD_TEMP;
	c->mq.client.el = ae_create_event_loop(5);
	init_protocol_context(&c->mq.client.buf_list);
}

void mq_before_sleep(AE_EVENT_LOOP * eventLoop) 
{
    UNUSED(eventLoop);
	SDK_CONTENT * c = &g_sdk_content;
	write_to_client(&c->mq.client);
}

void do_mq_main()
{
	SDK_CONTENT * c = &g_sdk_content;
	
	c->mq.client.fd = net_tcp_non_block_connect(c->mq.client.neterr, "192.168.1.174", 8888);
    net_enable_tcp_no_delay(NULL,c->mq.client.fd);
	
	if (c->mq.client.tcpkeepalive)
		net_keep_alive(NULL, c->mq.client.fd, c->mq.client.tcpkeepalive);
	
	if (ae_create_file_event(c->mq.client.el, c->mq.client.fd, AE_READABLE, read_data_from_server, &c->mq.client) == AE_ERR)
	{
		close(c->mq.client.fd);
		return;
	}
	
	ae_set_before_sleep_proc(c->mq.client.el, mq_before_sleep);
	
	while (!c->mq.client.el->stop) 
	{
		if (c->mq.client.el->before_sleep != NULL)
			c->mq.client.el->before_sleep(c->mq.client.el);
		ae_process_events(c->mq.client.el, AE_ALL_EVENTS);
	}

	ae_delete_event_loop(c->mq.client.el);
}

void deinit_mq()
{
	SDK_CONTENT * c = &g_sdk_content;
	deinit_protocol_context(&c->mq.client.buf_list);
	close(c->mq.client.fd);
	return;
}
